import json

from flask import Flask, request
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket

app = Flask(__name__)

socket_dict = {}

@app.route("/<username>")
def ws(username):
	user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
	if user_socket:
		socket_dict[username] = user_socket
	print(socket_dict)
	while 1:
		user_msg = user_socket.receive()
		#{"filename":"4d9b2cea-abe7-4161-a169-f05a89094d94.amr.mp3","to_user":"pq"}
		msg_dict = json.loads(user_msg)
		usocket = socket_dict.get(msg_dict.get("to_user"))
		usocket.send(user_msg)



if __name__ == '__main__':
	serv = WSGIServer(("0.0.0.0", 9528), app, handler_class=WebSocketHandler)
	serv.serve_forever()
